package com.lsmo.android.util;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBConnection {
	private SQLiteDatabase database;

	DBConnection(SQLiteDatabase database) {
		this.database = database;
	}

	public void beginTransaction() {
		database.beginTransaction();
	}

	public void commit() {
		database.setTransactionSuccessful();
		database.endTransaction();
	}

	public void rollbak() {
		database.endTransaction();
	}

	public void close() {
		database.close();
	}

	public ResultSet executeQuery(String sql, Object[] parameters)
			throws Exception {
		Cursor cursor = database.rawQuery(sql, (String[]) parameters);

		ResultSetMetaData metaData = new ResultSetMetaData(
				cursor.getColumnNames());
		ResultSet resultSet = new ResultSet(metaData);
		int columnCount = metaData.getColumnCount();
		while (cursor.moveToNext()) {
			Object[] row = new Object[columnCount];
			for (int i = 0; i < columnCount; i++) {
				row[i] = cursor.getString(i);
			}
			resultSet.addRow(row);
		}
		if (resultSet.getRowCount() > 0) {
			return resultSet;
		}
		return null;
	}

	public boolean executeUpdate(String sql, Object[] parameters)
			throws Exception {
		database.execSQL(sql, parameters);
		return true;
	}
}